package com.ruoyi.mall.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.mall.domain.Customer;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.mall.domain.vo.CustomerVo;
import com.ruoyi.mall.domain.bo.CustomerBo;
import com.ruoyi.mall.service.ICustomerService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 会员信息
 *
 * @author ruoyi
 * @date 2024-04-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mall/customer")
public class CustomerController extends BaseController {

    private final ICustomerService iCustomerService;


    /**
     * 查询会员信息列表
     */
    @SaCheckPermission("mall:customer:list")
    @GetMapping("/list")
    public TableDataInfo<CustomerVo> list(CustomerBo bo, PageQuery pageQuery) {
        return iCustomerService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出会员信息列表
     */
    @SaCheckPermission("mall:customer:export")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CustomerBo bo, HttpServletResponse response) {
        List<CustomerVo> list = iCustomerService.queryList(bo);
        ExcelUtil.exportExcel(list, "会员信息", CustomerVo.class, response);
    }

    /**
     * 获取会员信息详细信息
     *
     * @param customerId 主键
     */
    @SaCheckPermission("mall:customer:query")
    @GetMapping("/{customerId}")
    public R<CustomerVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long customerId) {
        return R.ok(iCustomerService.queryById(customerId));
    }

    /**
     * 新增会员信息
     */
    @SaCheckPermission("mall:customer:add")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CustomerBo bo) {
        return toAjax(iCustomerService.insertByBo(bo));
    }

    /**
     * 修改会员信息
     */
    @SaCheckPermission("mall:customer:edit")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CustomerBo bo) {
        return toAjax(iCustomerService.updateByBo(bo));
    }

    /**
     * 删除会员信息
     *
     * @param customerIds 主键串
     */
    @SaCheckPermission("mall:customer:remove")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] customerIds) {
        return toAjax(iCustomerService.deleteWithValidByIds(Arrays.asList(customerIds), true));
    }

    @SaIgnore
    @RequestMapping("/login")
    public R<Map<String, Object>> login(@RequestBody LoginBody loginBody)
    {
        Customer customer = new Customer();
        customer.setCustomerAccount(loginBody.getUsername());
        customer.setPassword(loginBody.getPassword());
        List<Customer> lstCustomer = iCustomerService.selectCustomerList(customer);
        if (lstCustomer.size() > 0)
        {
            iCustomerService.fillCustomerInfo(lstCustomer.get(0));
            Map<String, Object> ajax = new HashMap<>();
            ajax.put(Constants.TOKEN, StpUtil.getTokenValue());
            return R.ok(ajax);
        }
        return R.fail();
    }

    @SaIgnore
    @RequestMapping("/register")
    public R<Map<String, Object>> register(@RequestBody LoginBody loginBody)
    {
        Customer query = new Customer();
        query.setCustomerAccount(loginBody.getUsername());
        List<Customer> lstCustomer = iCustomerService.selectCustomerList(query);
        if (lstCustomer != null && lstCustomer.size() > 0)
        {
            return R.fail("用户信息已存在");
        }
        CustomerBo customerBo = new CustomerBo();
        customerBo.setCustomerAccount(loginBody.getUsername());
        customerBo.setPassword(loginBody.getPassword());
        if (iCustomerService.insertByBo(customerBo))
        {
            Customer customer = new Customer();
            BeanCopyUtils.copy(customerBo, customer);
            iCustomerService.fillCustomerInfo(customer);
            Map<String, Object> ajax = new HashMap<>();
            ajax.put(Constants.TOKEN, StpUtil.getTokenValue());
            return R.ok(ajax);
        }
        return R.fail();
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @SaIgnore
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Customer customer = iCustomerService.selectCustomerByCustomerId(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", customer);
        return R.ok(ajax);
    }

    /**
     * 获取当前登录的用户信息
     * @return
     */
    @SaIgnore
    @RequestMapping("/getCustomer")
    public R<CustomerVo> getCustomer(@RequestBody JSONObject json)
    {
        Long customerId =  Long.valueOf(json.get("customerId").toString());
        return R.ok(iCustomerService.queryById(customerId));
    }

    /**
     * 更新用户信息
     * @return
     */
    @SaIgnore
    @RequestMapping("/updateCustomer")
    public R<Void> updateCustomer(@RequestBody CustomerBo customerBo)
    {
        boolean result = iCustomerService.updateByBo(customerBo);
        if (result)
        {
           return R.ok("更新用户信息成功！");
        }
        return R.fail("更新用户信息失败！");
    }
}
